//
//  SNAddCarAnimation.m
//  ShunLand
//
//  Created by 冯贺 on 2018/3/27.
//  Copyright © 2018年 冯贺. All rights reserved.
//

#import "SNAddCarAnimation.h"

@implementation SNAddCarAnimation
+ (void)addToShoppingCartWithGoodsImage:(UIImage *)goodsImage startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint completion:(void (^)(BOOL))completion{
   
          //------- 创建shapeLayer -------//
            CAShapeLayer *animationLayer = [[CAShapeLayer alloc] init];
            animationLayer.frame = CGRectMake(startPoint.x - 20, startPoint.y - 20, 40, 40);
            animationLayer.contents = (id)goodsImage.CGImage;
    
            // 获取window的最顶层视图控制器
            UIViewController *rootVC = [[UIApplication sharedApplication].delegate window].rootViewController;
            UIViewController *parentVC = rootVC;
            while ((parentVC = rootVC.presentedViewController) != nil ) {
                    rootVC = parentVC;
                }
            while ([rootVC isKindOfClass:[UINavigationController class]]) {
                    rootVC = [(UINavigationController *)rootVC topViewController];
                }
    
            // 添加layer到顶层视图控制器上
            [rootVC.view.layer addSublayer:animationLayer];
    
    
            //------- 创建移动轨迹 -------//
            UIBezierPath *movePath = [UIBezierPath bezierPath];
            [movePath moveToPoint:startPoint];
            [movePath addQuadCurveToPoint:endPoint controlPoint:CGPointMake(200,100)];
            // 轨迹动画
            CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
            CGFloat durationTime = 1; // 动画时间1秒
            pathAnimation.duration = durationTime;
            pathAnimation.removedOnCompletion = NO;
            pathAnimation.fillMode = kCAFillModeForwards;
            pathAnimation.path = movePath.CGPath;
    
    
            //------- 创建缩小动画 -------//
            CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
            scaleAnimation.toValue = [NSNumber numberWithFloat:0.5];
            scaleAnimation.duration = 1.0;
            scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            scaleAnimation.removedOnCompletion = NO;
            scaleAnimation.fillMode = kCAFillModeForwards;
    
    
            // 添加轨迹动画
            [animationLayer addAnimation:pathAnimation forKey:nil];
            // 添加缩小动画
            [animationLayer addAnimation:scaleAnimation forKey:nil];
    
    
            //------- 动画结束后执行 -------//
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(durationTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [animationLayer removeFromSuperlayer];
                    completion(YES);
        });
}
@end
